<script lang="ts">
    import { entries } from "./store";
    import ChatEntryModel from "./ChatEntryModel";
    import axios from "axios";
    import type { AxiosResponse } from "axios";

    let value: string;
    let responseText = '';
    let copySuccessMessage = '';
    async function send() {
        console.log("Sending..." + value);
        let model = new ChatEntryModel();
        model.prompt = value;
        model.response = "正在思考...";
        entries.set([...$entries, model]);
        
        let answer = await fetchData({ "model": "qwen2", "prompt": model.prompt });
        model.response = answer;
        console.log(model.response);

        entries.set([...$entries]);
        value = "";
    }

        // 处理文本框的按键事件
    async function handleKeyDown(event) {
        if (event.key === 'Enter') {
        // 阻止默认行为（如表单提交）
        event.preventDefault();
        // 触发点击事件
        send();
        }
    }
    async function fetchData(data: object): Promise<string> {
        let answer: string = "";
        try {
            answer = "";
            const url = "http://localhost:11434/api/generate";

            const response: AxiosResponse<any, any> = await axios.post(
                url,
                data,
            );

            const json: string = response.data as string;
            const lines: string[] = json.split(/\r?\n/);

            for (const line of lines) {
                if (line.trim() !== "") {
                    const parsedline = JSON.parse(line);
                    if (parsedline.done == false) {
                        answer += parsedline.response;
                    }
                }
            }
            console.log("Answer:", answer); // Log final answer
            responseText = answer;

        } catch (error) {
            console.error("Error fetching data:", error);
        }

        return answer;
    }
    const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(responseText);
      copySuccessMessage = '已复制到剪贴板！';
    } catch (err) {
      console.error('无法复制到剪贴板:', err);
      copySuccessMessage = '复制失败，请手动复制。';
    }
  };
</script>

<div>
    <input type="text" on:keydown={handleKeyDown} bind:value />
    <button on:click={send}>发送</button>
    <button on:click={copyToClipboard}>复制到剪贴板</button>
</div>

